<template>
  <div class="approval-page">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-4">
        <el-card shadow="hover" class="search-card">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="模板名称" prop="templateName">
              <el-input v-model="queryParams.templateName" placeholder="请输入模板名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="模板类型" prop="templateType">
              <el-input v-model="queryParams.templateType" placeholder="请输入模板类型" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="是否启用" prop="isActive">
              <el-select v-model="queryParams.isActive" placeholder="请选择是否启用" clearable>
                <el-option v-for="dict in approval_template_active" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="" class="date-range-item">
              <el-date-picker
                v-model="dateRangeCreateTime"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never" class="main-card">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['approval:flowTemplate:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['approval:flowTemplate:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['approval:flowTemplate:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['approval:flowTemplate:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="ApprovalFlowTemplateList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="模板名称" align="center" prop="templateName" show-overflow-tooltip />
        <el-table-column label="模板类型" align="center" prop="templateType" width="120" show-overflow-tooltip />
        <el-table-column label="模板描述" align="center" prop="description" show-overflow-tooltip />
        <el-table-column label="阶段数量" align="center" prop="stageCount" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.stageCount > 0" type="primary">{{ scope.row.stageCount }} 个阶段</el-tag>
            <el-tag v-else type="info">暂无阶段</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="是否启用" align="center" prop="isActive">
          <template #default="scope">
            <dict-tag :options="approval_template_active" :value="scope.row.isActive" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建人" align="center" prop="createBy" width="100">
          <template #default="scope">
            <span>{{ scope.row.createName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['approval:flowTemplate:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['approval:flowTemplate:remove']"></el-button>
            </el-tooltip>
            <el-tooltip content="查看" placement="top">
              <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['approval:flowTemplate:query']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 添加或修改审核流程模板对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="1200px" append-to-body>
      <el-form ref="ApprovalFlowTemplateFormRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="模板名称" prop="templateName">
              <el-input v-model="form.templateName" placeholder="请输入模板名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模板类型" prop="templateType">
              <el-input v-model="form.templateType" placeholder="请输入模板类型" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="是否启用" prop="isActive">
              <el-radio-group v-model="form.isActive">
                <el-radio v-for="dict in approval_template_active" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="模板描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入模板描述" :rows="3" />
        </el-form-item>

        <!-- 审核流程步骤配置 -->
        <el-divider content-position="left">
          <span>自定义审核流程</span>
          <el-tag v-if="stageCount > 0" type="primary" class="ml-2">当前共 {{ stageCount }} 个阶段</el-tag>
          <el-tag v-else type="info" class="ml-2">暂无阶段</el-tag>
        </el-divider>

        <div>
          <!-- 步骤条展示 -->
          <el-steps :active="activeStep" align-center class="workflow-steps" v-if="form.stageList && form.stageList.length > 0">
            <el-step
              v-for="(stage, index) in form.stageList"
              :key="index"
              :title="stage.stageName || `步骤${index + 1}`"
              :description="stage.stageDescription"
            />
          </el-steps>

          <!-- 阶段列表 -->
          <div v-if="form.stageList && form.stageList.length > 0" class="stage-list">
            <div v-for="(stage, index) in form.stageList" :key="index" class="stage-item" @click="setActiveStep(index)">
              <el-card shadow="hover" class="stage-card">
                <template #header>
                  <div class="stage-header">
                    <span class="stage-title">
                      <el-icon class="stage-icon"><Document /></el-icon>
                      第{{ index + 1 }}步：{{ stage.stageName || '未命名' }}
                    </span>
                    <div class="stage-actions">
                      <el-button size="small" type="primary" link @click.stop="editStage(index)">
                        <el-icon><Edit /></el-icon>
                      </el-button>
                      <el-button size="small" type="danger" link @click.stop="removeStage(index)">
                        <el-icon><Delete /></el-icon>
                      </el-button>
                    </div>
                  </div>
                </template>

                <div>
                  <el-row :gutter="20">
                    <el-col :span="8">
                      <div>
                        <span>审核规则：</span>
                        <el-tag :type="getApprovalRuleType(stage.approvalRule)">
                          {{ getApprovalRuleText(stage.approvalRule) }}
                        </el-tag>
                      </div>
                    </el-col>
                    <el-col :span="8" v-if="stage.approvalRule === '2'">
                      <div>
                        <span>通过比例：</span>
                        <span>{{ ((stage.passRatio || 0) * 100).toFixed(1) }}%</span>
                      </div>
                    </el-col>
                    <el-col :span="8">
                      <div>
                        <span>是否必须：</span>
                        <el-tag :type="stage.isRequired === '1' ? 'danger' : 'info'">
                          {{ stage.isRequired === '1' ? '必须' : '非必须（暂未开放）' }}
                        </el-tag>
                      </div>
                    </el-col>
                    <el-col :span="8">
                      <div>
                        <span>固定审核人员：</span>
                        <el-tag :type="stage.fixationApprover === '1' ? 'warning' : 'success'">
                          {{ stage.fixationApprover === '1' ? '固定' : '不固定' }}
                        </el-tag>
                      </div>
                    </el-col>
                  </el-row>

                  <!-- 预设审核人员显示 -->
                  <div class="approvers-section">
                    <span>预设审核人员：</span>
                    <div v-if="stage.approversId && stage.approversId.trim()" class="approvers-display">
                      <div class="approvers-tags">
                        <el-tag
                          v-for="(userName, approverIndex) in getApproversDisplay(stage)"
                          :key="approverIndex"
                          type="primary"
                          size="small"
                          class="approver-tag"
                        >
                          <el-icon><User /></el-icon>
                          {{ userName.trim() }}
                        </el-tag>
                      </div>
                      <el-button size="small" type="primary" link @click.stop="selectApproversForStage(index)">
                        <el-icon><Edit /></el-icon>
                        修改审核人员
                      </el-button>
                    </div>
                    <div v-else>
                      <el-tag type="info" size="small">暂未设置</el-tag>
                      <el-button size="small" type="primary" link @click.stop="selectApproversForStage(index)">
                        <el-icon><Plus /></el-icon>
                        选择审核人员
                      </el-button>
                    </div>
                  </div>

                  <!-- 抄送人员显示 -->
                  <div class="approvers-section">
                    <span>抄送人员：</span>
                    <div v-if="stage.ccApproversId && stage.ccApproversId.trim()" class="approvers-display">
                      <div class="approvers-tags">
                        <el-tag
                          v-for="(userName, approverIndex) in getCcApproversDisplay(stage)"
                          :key="approverIndex"
                          type="primary"
                          size="small"
                          class="approver-tag"
                        >
                          <el-icon><User /></el-icon>
                          {{ userName.trim() }}
                        </el-tag>
                      </div>
                      <el-button size="small" type="primary" link @click.stop="selectCcApproversForStage(index)">
                        <el-icon><Edit /></el-icon>
                        修改抄送人员
                      </el-button>
                    </div>
                    <div v-else>
                      <el-tag type="info" size="small">暂未设置</el-tag>
                      <el-button size="small" type="primary" link @click.stop="selectCcApproversForStage(index)">
                        <el-icon><Plus /></el-icon>
                        选择抄送人员
                      </el-button>
                    </div>
                  </div>

                  <div v-if="stage.stageDescription">
                    <span>描述：</span>
                    {{ stage.stageDescription }}
                  </div>
                </div>
              </el-card>
            </div>
          </div>

          <!-- 添加阶段按钮 -->
          <div class="add-stage-btn">
            <el-button type="primary" @click="addStage">
              <el-icon><Plus /></el-icon>
              添加审核阶段
            </el-button>
          </div>
        </div>
      </el-form>

      <template #footer>
        <div>
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog title="审核流程模板详情" v-model="viewDialog.visible" width="1200px" append-to-body>
      <div v-if="viewData">
        <el-descriptions :column="2" border size="large">
          <el-descriptions-item label="模板名称">
            {{ viewData.templateName }}
          </el-descriptions-item>
          <el-descriptions-item label="模板类型">
            {{ viewData.templateType }}
          </el-descriptions-item>
          <el-descriptions-item label="阶段数量">
            <el-tag v-if="viewData.stageCount > 0" type="primary">{{ viewData.stageCount }} 个阶段</el-tag>
            <el-tag v-else type="info">暂无阶段</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="是否启用">
            <dict-tag :options="approval_template_active" :value="viewData.isActive" />
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ parseTime(viewData.createTime, '{y}-{m}-{d}') }}
          </el-descriptions-item>
          <el-descriptions-item label="创建人">
            {{ viewData.createName }}
          </el-descriptions-item>
          <el-descriptions-item label="模板描述" :span="2">
            {{ viewData.description || '暂无描述' }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 审核流程步骤展示 -->
        <el-divider content-position="left">
          <span>审核流程详情</span>
        </el-divider>

        <div v-if="viewData.stageList && viewData.stageList.length > 0">
          <!-- 步骤条展示 -->
          <el-steps align-center class="workflow-steps">
            <el-step
              v-for="(stage, index) in viewData.stageList"
              :key="index"
              :title="stage.stageName || `步骤${index + 1}`"
              :description="stage.stageDescription"
              status="finish"
            />
          </el-steps>

          <!-- 阶段详情列表 -->
          <div class="stage-list">
            <div v-for="(stage, index) in viewData.stageList" :key="index" class="stage-item">
              <el-card shadow="hover" class="stage-card">
                <template #header>
                  <div class="stage-header">
                    <span class="stage-title">
                      <el-icon class="stage-icon"><Document /></el-icon>
                      第{{ index + 1 }}步：{{ stage.stageName || '未命名' }}
                    </span>
                  </div>
                </template>

                <div>
                  <el-row :gutter="20">
                    <el-col :span="8">
                      <div>
                        <span>审核规则：</span>
                        <el-tag :type="getApprovalRuleType(stage.approvalRule)">
                          {{ getApprovalRuleText(stage.approvalRule) }}
                        </el-tag>
                      </div>
                    </el-col>
                    <el-col :span="8" v-if="stage.approvalRule === '2'">
                      <div>
                        <span>通过比例：</span>
                        <span>{{ ((stage.passRatio || 0) * 100).toFixed(1) }}%</span>
                      </div>
                    </el-col>
                    <el-col :span="8">
                      <div>
                        <span>是否必须：</span>
                        <el-tag :type="stage.isRequired === '1' ? 'danger' : 'info'">
                          {{ stage.isRequired === '1' ? '必须' : '非必须' }}
                        </el-tag>
                      </div>
                    </el-col>
                    <el-col :span="8">
                      <div>
                        <span>固定审核人员：</span>
                        <el-tag :type="stage.fixationApprover === '1' ? 'warning' : 'success'">
                          {{ stage.fixationApprover === '1' ? '固定' : '不固定' }}
                        </el-tag>
                      </div>
                    </el-col>
                  </el-row>

                  <!-- 预设审核人员显示（详情页面） -->
                  <div class="approvers-section">
                    <span>预设审核人员：</span>
                    <div v-if="stage.approversId && stage.approversId.trim()" class="approvers-tags">
                      <el-tag
                        v-for="(userName, approverIndex) in getApproversDisplay(stage)"
                        :key="approverIndex"
                        type="primary"
                        size="small"
                        class="approver-tag"
                      >
                        <el-icon><User /></el-icon>
                        {{ userName.trim() }}
                      </el-tag>
                    </div>
                    <div v-else>
                      <el-tag type="info" size="small">暂未设置</el-tag>
                    </div>
                  </div>

                  <!-- 预设抄送人员显示（详情页面） -->
                  <div class="approvers-section">
                    <span>抄送人员：</span>
                    <div v-if="stage.ccApproversId && stage.ccApproversId.trim()" class="approvers-tags">
                      <el-tag
                        v-for="(userName, approverIndex) in getCcApproversDisplay(stage)"
                        :key="approverIndex"
                        type="primary"
                        size="small"
                        class="approver-tag"
                      >
                        <el-icon><User /></el-icon>
                        {{ userName.trim() }}
                      </el-tag>
                    </div>
                    <div v-else>
                      <el-tag type="info" size="small">暂未设置</el-tag>
                    </div>
                  </div>

                  <div v-if="stage.stageDescription">
                    <span>描述：</span>
                    {{ stage.stageDescription }}
                  </div>
                </div>
              </el-card>
            </div>
          </div>
        </div>
        <div v-else>
          <el-empty description="暂无审核阶段配置" />
        </div>
      </div>

      <template #footer>
        <div>
          <el-button @click="viewDialog.visible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑审核阶段对话框 -->
    <el-dialog
      title="编辑审核阶段"
      v-model="stageDialog.visible"
      width="800px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      destroy-on-close
      @closed="onStageDialogClosed"
    >
      <el-form ref="stageFormRef" :model="currentStage" :rules="stageRules" label-width="120px">
        <el-form-item label="阶段名称" prop="stageName">
          <el-input v-model="currentStage.stageName" placeholder="请输入阶段名称" />
        </el-form-item>

        <el-form-item label="审核规则" prop="approvalRule">
          <el-radio-group v-model="currentStage.approvalRule">
            <el-radio value="0">全员通过</el-radio>
            <el-radio value="1" disabled>一人通过（暂未开放）</el-radio>
            <el-radio value="2" disabled>按比例通过（暂未开放）</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="通过比例" prop="passRatio" v-if="currentStage.approvalRule === '2'">
          <el-input-number v-model="currentStage.passRatio" :min="0.1" :max="1" :step="0.1" :precision="1" placeholder="请输入通过比例" />
          <span class="ratio-tip">（取值范围：0.1-1.0）</span>
        </el-form-item>

        <el-form-item label="是否必须" prop="isRequired">
          <el-radio-group v-model="currentStage.isRequired">
            <el-radio value="1">必须</el-radio>
            <el-radio value="0" disabled>非必须（暂未开放）</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="固定审核人员" prop="fixationApprover">
          <el-radio-group v-model="currentStage.fixationApprover">
            <el-radio value="0">不固定</el-radio>
            <el-radio value="1">固定</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 预设审核人员选择 -->
        <el-form-item label="预设审核人员">
          <div class="approvers-input-section">
            <div v-if="currentStageApprovers.length > 0" class="selected-approvers">
              <el-tag
                v-for="(approver, index) in currentStageApprovers"
                :key="index"
                type="primary"
                size="small"
                closable
                @close="removeCurrentStageApprover(index)"
                class="approver-tag"
              >
                <el-icon><User /></el-icon>
                {{ approver.userName }}
              </el-tag>
            </div>
            <div class="approver-actions">
              <el-button type="primary" plain @click="selectApproversForCurrentStage">
                <el-icon><Plus /></el-icon>
                {{ currentStageApprovers.length > 0 ? '修改审核人员' : '选择审核人员' }}
              </el-button>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="抄送人员">
          <div class="approvers-input-section">
            <div v-if="currentCcStageApprovers.length > 0" class="selected-approvers">
              <el-tag
                v-for="(approver, index) in currentCcStageApprovers"
                :key="index"
                type="primary"
                size="small"
                closable
                @close="removeCurrentCcApprover(index)"
                class="approver-tag"
              >
                <el-icon><User /></el-icon>
                {{ approver.userName }}
              </el-tag>
            </div>
            <div class="approver-actions">
              <el-button type="primary" plain @click="selectCcApproversForCurrentStage">
                <el-icon><Plus /></el-icon>
                {{ currentStageApprovers.length > 0 ? '修改抄送人员' : '选择抄送人员' }}
              </el-button>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="阶段描述" prop="stageDescription">
          <el-input v-model="currentStage.stageDescription" type="textarea" placeholder="请输入阶段描述" :rows="3" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div>
          <el-button type="primary" @click="saveStage">确 定</el-button>
          <el-button @click="cancelStageEdit">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 用户选择器 -->
    <UserSelector
      v-model:visible="userSelectorVisible"
      title="选择审核人员"
      :selectedUserIds="selectedUserIds"
      :selectedUserNames="selectedUserNames"
      :multiple="true"
      @confirmWithIds="handleUserSelectionConfirm"
      @cancel="handleUserSelectionCancel"
    />

    <!-- 抄送用户选择器 -->
    <UserSelector
      v-model:visible="userCcSelectorVisible"
      title="选择审核人员"
      :selectedUserIds="selectedCcUserIds"
      :selectedUserNames="selectedCcUserNames"
      :multiple="true"
      @confirmWithIds="handleCcUserSelectionConfirm"
      @cancel="handleCcUserSelectionCancel"
    />
  </div>
</template>

<script setup name="ApprovalFlowTemplate" lang="ts">
import {
  listApprovalFlowTemplate,
  getApprovalFlowTemplate,
  delApprovalFlowTemplate,
  addApprovalFlowTemplate,
  updateApprovalFlowTemplate
} from '@/api/other/approval/index';
import { ApprovalFlowTemplateVO, ApprovalFlowTemplateQuery, ApprovalFlowTemplateForm, ApprovalStageTemplateForm } from '@/api/other/approval/types';
import { Plus, Edit, Delete, Document, View, User } from '@element-plus/icons-vue';
import { parseTime } from '@/utils/ruoyi';
import UserSelector from '@/components/UserSelector/index.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { approval_template_active } = toRefs<any>(proxy?.useDict('approval_template_active'));

const ApprovalFlowTemplateList = ref<ApprovalFlowTemplateVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRangeCreateTime = ref<[DateModelType, DateModelType]>(['', '']);
const activeStep = ref(0);
const currentStageIndex = ref(-1);

// 用户选择器相关数据
const userSelectorVisible = ref(false);
const selectedUserIds = ref('');
const selectedUserNames = ref('');
const currentSelectingStageIndex = ref(-1);
const currentStageApprovers = ref<any[]>([]);

// 抄送人员
const userCcSelectorVisible = ref(false);   // 抄送人员选择器显示状态
const selectedCcUserIds = ref('');          // 抄送人员已选用户id
const selectedCcUserNames = ref('');        // 抄送人员已选用户名
const currentCcSelectingStageIndex = ref(-1);
const currentCcStageApprovers = ref<any[]>([]);

const queryFormRef = ref<ElFormInstance>();
const ApprovalFlowTemplateFormRef = ref<ElFormInstance>();
const stageFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const stageDialog = reactive({
  visible: false
});

const viewDialog = reactive({
  visible: false
});

const viewData = ref<ApprovalFlowTemplateVO | null>(null);

const initFormData: ApprovalFlowTemplateForm = {
  id: undefined,
  templateName: undefined,
  templateType: undefined,
  description: undefined,
  isActive: '1',
  stageCount: 0,
  stageList: []
};

const initStageData: ApprovalStageTemplateForm = {
  stageName: '',
  stageSort: 1,
  approvalRule: '0',
  passRatio: 0.6,
  isRequired: '1',
  stageDescription: '',
  approversId: '',
  approversName: '',
  fixationApprover: '0' // 0-不固定，1-固定
};

const currentStage = ref<ApprovalStageTemplateForm>({ ...initStageData });

const data = reactive<PageData<ApprovalFlowTemplateForm, ApprovalFlowTemplateQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    templateName: undefined,
    templateType: undefined,
    isActive: undefined,
    params: {
      createTime: undefined
    }
  },
  rules: {
    templateName: [{ required: true, message: '模板名称不能为空', trigger: 'blur' }],
    templateType: [{ required: true, message: '模板类型不能为空', trigger: 'blur' }],
    isActive: [{ required: true, message: '请选择是否启用', trigger: 'change' }]
  }
});

// 1. 修复校验规则，移除有问题的自定义校验器
const stageRules = reactive({
  stageName: [{ required: true, message: '阶段名称不能为空', trigger: 'blur' }],
  approvalRule: [{ required: true, message: '请选择审核规则', trigger: 'change' }],
  isRequired: [{ required: true, message: '请选择是否必须', trigger: 'change' }],
  fixationApprover: [{ required: true, message: '请选择是否固定审核人员', trigger: 'change' }]
});

const { queryParams, form, rules } = toRefs(data);

// 计算属性：自动计算阶段数量
const stageCount = computed(() => {
  return form.value.stageList?.length || 0;
});

/** 获取审核规则文本 */
const getApprovalRuleText = (rule: string) => {
  const map: Record<string, string> = {
    '0': '全员通过',
    '1': '一人通过（暂未开放）',
    '2': '按比例通过（暂未开放）'
  };
  return map[rule] || '未知';
};

/** 获取审核规则标签类型 */
const getApprovalRuleType = (rule: string) => {
  const map: Record<string, 'success' | 'warning' | 'primary' | 'info' | 'danger'> = {
    '0': 'success',
    '1': 'info',
    '2': 'info'
  };
  return map[rule] || 'info';
};

/** 设置当前激活步骤 */
const setActiveStep = (index: number) => {
  activeStep.value = index;
};

/** 为指定阶段选择审核人员 */
const selectApproversForStage = (stageIndex: number) => {
  const stage = form.value.stageList?.[stageIndex];
  if (!stage) return;

  currentSelectingStageIndex.value = stageIndex;
  selectedUserIds.value = stage.approversId || '';
  selectedUserNames.value = stage.approversName || '';
  userSelectorVisible.value = true;
};

/** 为当前编辑的阶段选择审核人员 */
const selectApproversForCurrentStage = () => {
  currentSelectingStageIndex.value = -1;
  selectedUserIds.value = currentStage.value.approversId || '';
  selectedUserNames.value = currentStage.value.approversName || '';
  userSelectorVisible.value = true;
};

/** 移除当前阶段的指定审核人员 */
const removeCurrentStageApprover = (index: number) => {
  currentStageApprovers.value.splice(index, 1);
  currentStage.value.approversId = currentStageApprovers.value.map((user) => user.userId).join(',');
  currentStage.value.approversName = currentStageApprovers.value.map((user) => user.nickName || user.userName).join(',');
};

/** 获取审核人员显示信息 */
const getApproversDisplay = (stage: any) => {
  if (!stage.approversId) return [];

  if (stage.approversName && stage.approversName.trim()) {
    return stage.approversName.split(',');
  }

  return stage.approversId.split(',').map((id: string) => `用户ID: ${id.trim()}`);
};

/** 用户选择确认回调 */
const handleUserSelectionConfirm = (data: { users: any[]; userIds: string; userNames: string }) => {
  if (currentSelectingStageIndex.value === -1) {
    currentStage.value.approversId = data.userIds;
    currentStage.value.approversName = data.userNames;
    currentStageApprovers.value = data.users;
  } else {
    const stage = form.value.stageList?.[currentSelectingStageIndex.value];
    if (stage) {
      stage.approversId = data.userIds;
      stage.approversName = data.userNames;
    }
  }

  userSelectorVisible.value = false;
  proxy?.$modal.msgSuccess(`已选择 ${data.users.length} 名审核人员`);
};

/** 用户选择取消回调 */
const handleUserSelectionCancel = () => {
  userSelectorVisible.value = false;
  currentSelectingStageIndex.value = -1;
  selectedUserIds.value = '';
  selectedUserNames.value = '';
};

/** 添加审核阶段 */
const addStage = () => {
  currentStage.value = {
    ...initStageData,
    stageSort: (form.value.stageList?.length || 0) + 1
  };
  currentStageIndex.value = -1;
  currentStageApprovers.value = [];

  nextTick(() => {
    stageFormRef.value?.resetFields();
    stageDialog.visible = true;
  });
};

/** 编辑审核阶段 */
const editStage = (index: number) => {
  currentStage.value = { ...form.value.stageList![index] };
  currentStageIndex.value = index;
  currentStageApprovers.value = [];

  // 如果有预设审核人员，初始化显示
  if (currentStage.value.approversId && currentStage.value.approversName) {
    const userIds = currentStage.value.approversId.split(',');
    const userNames = currentStage.value.approversName.split(',');
    currentStageApprovers.value = userIds.map((id, index) => ({
      userId: id.trim(),
      nickName: userNames[index]?.trim() || `用户${id.trim()}`,
      userName: userNames[index]?.trim() || `用户${id.trim()}`
    }));
  }

  // 如果有预设抄送人员，初始化显示
  if (currentStage.value.ccApproversId && currentStage.value.ccApproversName) {
    const ccIds = currentStage.value.ccApproversId.split(',');
    const ccNames = currentStage.value.ccApproversName.split(',');
    currentCcStageApprovers.value = ccIds.map((id, idx) => ({
      userId: id.trim(),
      nickName: ccNames[idx]?.trim() || `用户${id.trim()}`,
      userName: ccNames[idx]?.trim() || `用户${id.trim()}`
    }));
  }

  nextTick(() => {
    stageDialog.visible = true;
  });
};

/** 删除审核阶段 */
const removeStage = (index: number) => {
  proxy?.$modal
    .confirm('确定要删除这个审核阶段吗？')
    .then(() => {
      form.value.stageList!.splice(index, 1);

      // 重新排序
      form.value.stageList!.forEach((stage, idx) => {
        stage.stageSort = idx + 1;
      });

      // 调整当前激活步骤
      if (activeStep.value >= form.value.stageList!.length) {
        activeStep.value = Math.max(0, form.value.stageList!.length - 1);
      }
      proxy?.$modal.msgSuccess('删除成功');
    })
    .catch(() => {});
};

/** 保存审核阶段 */
const saveStage = () => {
  if (!stageFormRef.value) {
    proxy?.$modal.msgError('表单引用未找到');
    return;
  }
  stageFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      proxy?.$modal.msgError('请完善表单信息');
      return;
    }
    // 固定审核人员必须设置预设审核人员
    if (
      currentStage.value.fixationApprover === '1' &&
      (!currentStageApprovers.value || currentStageApprovers.value.length === 0)
    ) {
      proxy?.$modal.msgError('固定审核人员时必须设置预设审核人员');
      return;
    }
    try {
      // 同步审核人员
      currentStage.value.approversId = currentStageApprovers.value.map(u => u.userId).join(',');
      currentStage.value.approversName = currentStageApprovers.value.map(u => u.userName || u.nickName).join(',');
      // 同步抄送人员
      currentStage.value.ccApproversId = currentCcStageApprovers.value.map(u => u.userId).join(',');
      currentStage.value.ccApproversName = currentCcStageApprovers.value.map(u => u.userName || u.nickName).join(',');
      // 保存阶段到 stageList
      if (currentStageIndex.value === -1) {
        if (!form.value.stageList) form.value.stageList = [];
        form.value.stageList.push({ ...currentStage.value });
      } else {
        if (form.value.stageList && form.value.stageList[currentStageIndex.value]) {
          form.value.stageList[currentStageIndex.value] = { ...currentStage.value };
        } else {
          proxy?.$modal.msgError('阶段数据异常');
          return;
        }
      }
      stageDialog.visible = false;
      proxy?.$modal.msgSuccess('保存成功');
    } catch (error) {
      console.error('保存阶段失败:', error);
      proxy?.$modal.msgError('保存失败，请重试');
    }
  });
};


/** 取消阶段编辑 */
const cancelStageEdit = () => {
  currentStage.value = { ...initStageData };
  currentStageIndex.value = -1;
  stageFormRef.value?.resetFields();
  stageDialog.visible = false;
  currentStageApprovers.value = [];
  currentCcStageApprovers.value = [];
};

/** 阶段弹框关闭时的处理 */
const onStageDialogClosed = () => {
  currentStage.value = { ...initStageData };
  currentStageIndex.value = -1;
  currentStageApprovers.value = [];
  currentCcStageApprovers.value = [];
};

/** 查询审核流程模板列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.params = {};
  proxy?.addDateRange(queryParams.value, dateRangeCreateTime.value, 'CreateTime');
  const res = await listApprovalFlowTemplate(queryParams.value);
  ApprovalFlowTemplateList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  activeStep.value = 0;
  ApprovalFlowTemplateFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRangeCreateTime.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ApprovalFlowTemplateVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加审核流程模板';
};

/** 查看按钮操作 */
const handleView = async (row: ApprovalFlowTemplateVO) => {
  const res = await getApprovalFlowTemplate(row.id);
  viewData.value = res.data;
  viewDialog.visible = true;
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ApprovalFlowTemplateVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getApprovalFlowTemplate(_id);
  Object.assign(form.value, res.data);
  if (!form.value.stageList) {
    form.value.stageList = [];
  }
  dialog.visible = true;
  dialog.title = '修改审核流程模板';
};

/** 提交按钮 */
const submitForm = () => {
  ApprovalFlowTemplateFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (!form.value.stageList || form.value.stageList.length === 0) {
        proxy?.$modal.msgError('请至少添加一个审核阶段');
        return;
      }

      // 确保阶段排序正确
      form.value.stageList.forEach((stage, index) => {
        stage.stageSort = index + 1;
      });

      buttonLoading.value = true;
      try {
        if (form.value.id) {
          await updateApprovalFlowTemplate(form.value);
          proxy?.$modal.msgSuccess(`修改成功！模板共包含 ${form.value.stageList.length} 个审核阶段`);
        } else {
          await addApprovalFlowTemplate(form.value);
          proxy?.$modal.msgSuccess(`新增成功！模板共包含 ${form.value.stageList.length} 个审核阶段`);
        }
        dialog.visible = false;
        await getList();
      } catch (error) {
        console.error('提交失败:', error);
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: ApprovalFlowTemplateVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除审核流程模板编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delApprovalFlowTemplate(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'approval/flowTemplate/export',
    {
      ...queryParams.value
    },
    `ApprovalFlowTemplate_${new Date().getTime()}.xlsx`
  );
};

/** 打开当前阶段抄送人员选择器 */
const selectCcApproversForCurrentStage = () => {
  currentCcSelectingStageIndex.value = -1;
  selectedCcUserIds.value = currentStage.value.ccApproversId || '';
  selectedCcUserNames.value = currentStage.value.ccApproversName || '';
  userCcSelectorVisible.value = true;
};

/** 确认抄送人员选择 */
const handleCcUserSelectionConfirm = (data: { users: any[]; userIds: string; userNames: string }) => {
  if (currentCcSelectingStageIndex.value === -1) {
    currentStage.value.ccApproversId = data.userIds;
    currentStage.value.ccApproversName = data.userNames;
    currentCcStageApprovers.value = data.users;
  } else {
    const stage = form.value.stageList?.[currentCcSelectingStageIndex.value];
    if (stage) {
      stage.ccApproversId = data.userIds;
      stage.ccApproversName = data.userNames;
    }
  }
  userCcSelectorVisible.value = false;
  proxy?.$modal.msgSuccess(`已选择 ${data.users.length} 名抄送人员`);
};

/** 取消选择抄送人员 */
const handleCcUserSelectionCancel = () => {
  userCcSelectorVisible.value = false;
  currentCcSelectingStageIndex.value = -1;
  selectedCcUserIds.value = '';
  selectedCcUserNames.value = '';
};

/** 移除当前阶段抄送人员 */
const removeCurrentCcApprover = (index: number) => {
  currentCcStageApprovers.value.splice(index, 1);
  currentStage.value.ccApproversId = currentCcStageApprovers.value.map(u => u.userId).join(',');
  currentStage.value.ccApproversName = currentCcStageApprovers.value.map(u => u.nickName || u.userName).join(',');
};

/** 为指定阶段选择抄送人员 */
const selectCcApproversForStage = (stageIndex: number) => {
  const stage = form.value.stageList?.[stageIndex];
  if (!stage) return;

  currentCcSelectingStageIndex.value = stageIndex;
  selectedCcUserIds.value = stage.ccApproversId || '';
  selectedCcUserNames.value = stage.ccApproversName || '';
  userCcSelectorVisible.value = true; // 对应抄送人员选择器的 visible
};

/** 获取抄送人员显示信息 */
const getCcApproversDisplay = (stage: any) => {
  if (!stage.ccApproversId) return [];

  if (stage.ccApproversName && stage.ccApproversName.trim()) {
    return stage.ccApproversName.split(',');
  }

  return stage.ccApproversId.split(',').map((id: string) => `用户ID: ${id.trim()}`);
};

onMounted(() => {
  getList();
});
</script>

<style scoped>
.workflow-steps {
  margin-bottom: 24px;
}

.stage-list {
  margin-top: 20px;
}

.stage-item {
  margin-bottom: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.stage-item:hover {
  transform: translateY(-2px);
}

.stage-card {
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.stage-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stage-title {
  display: flex;
  align-items: center;
  font-weight: 600;
  font-size: 16px;
}

.stage-icon {
  margin-right: 8px;
  font-size: 18px;
}

.stage-actions {
  display: flex;
  gap: 8px;
}

.stage-item .el-row .el-col > div {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.stage-item .el-row .el-col > div > span:first-child {
  font-weight: 500;
  margin-right: 8px;
  min-width: 80px;
}

.stage-item > .el-card > .el-card__body > div:last-child {
  margin-top: 16px;
  padding-top: 16px;
  line-height: 1.6;
}

.stage-item > .el-card > .el-card__body > div:last-child > span:first-child {
  font-weight: 500;
  margin-right: 8px;
}

.ratio-tip {
  margin-left: 12px;
  font-size: 13px;
}

.date-range-item {
  width: 308px;
}

.add-stage-btn {
  text-align: center;
  margin-top: 20px;
}

.approvers-section {
  margin-top: 16px;
  margin-bottom: 16px;
}

.approvers-display {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.approvers-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 8px;
}

.approvers-input-section {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.selected-approvers {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.approver-tag {
  margin: 0;
}

.approver-actions {
  display: flex;
  align-items: center;
}
</style>
